//
//  CircularBufferController.m
//  INFSWA02
//
//  Created by Justin van Grootveld on 10/16/11.
//  Copyright (c) 2011 Pro4all. All rights reserved.
//

#import "CircularBufferController.h"
#import "Command.h"

@implementation CircularBufferController
@synthesize size = _size;

- (id)initWithBufferSize:(NSInteger)size
{
    if(self = [super init])
    {
        _size = size;
        _circularBuffer = [[NSMutableArray alloc] initWithCapacity:size];
        
        for(int i=0; i < _size; i++)
            [_circularBuffer addObject:[NSNull null]];
        
        _index = 0;
    }
    
    return self;
}

- (void)enqueueObject:(Command *)command
{
    [_circularBuffer replaceObjectAtIndex:_index withObject:command];
    
    //INDEX
    if(_index < _size-1) 
        _index++;
    else 
        _index = 0;
}

- (Command *)dequeue
{
    //INDEX
    if(_index > 0) 
        _index--;
    else 
        _index = _size-1;
    
    Command *command = [_circularBuffer objectAtIndex:_index];
    [_circularBuffer replaceObjectAtIndex:_index withObject:[NSNull null]];
    
    return command;
}

- (BOOL)hasObjects
{
    for(NSMutableArray *grid in _circularBuffer)
    {
        if(grid != nil) return YES;
    }
    
    return NO;
}

- (NSString *)description
{
    return [_circularBuffer description];
}

- (void)print
{
    NSLog(@"Print circular buffer");
    
    for(id obj in _circularBuffer)
    {
        NSLog(@"\t%@", [obj class]);
    }
}

@end
